package com.yuyou.train.admin.service.impl;

import java.util.Date;

import org.slf4j.Logger;  import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.emay.sdk.client.api.Client;

import com.yuyou.train.admin.service.ICommKeyConfigService;
import com.yuyou.train.admin.service.ICommSmsVerCodeService;
import com.yuyou.train.admin.service.ISmsService;
import com.yuyou.train.service.api.admin.entity.CommKeyConfig;
import com.yuyou.train.service.api.admin.entity.CommSmsVerCode;
import com.yuyou.train.util.message.admin.CommSmsVerCodeMess;

/**
 * Sms 表数据服务层接口实现类
 */
@Service
public class SmsServiceImpl implements ISmsService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ICommKeyConfigService commKeyConfigService;

	@Autowired
	private ICommSmsVerCodeService commSmsVerCodeService;

	@Override
	public int sendCode(String phoneNo, String type, String code) {

		int sendResult = 1;
		try {
			String[] phoneNos = new String[] { phoneNo };
			CommKeyConfig smsSpiNoConfig = commKeyConfigService
					.selectByDataKey("sms_spi_no");
			String smsSpiNo = smsSpiNoConfig.getDataValue();
			CommKeyConfig smsSpiPasswordConfig = commKeyConfigService
					.selectByDataKey("sms_spi_password");
			String smsSpiPassword = smsSpiPasswordConfig.getDataValue();

			Client client = new Client(smsSpiNo, smsSpiPassword);

			CommKeyConfig sms_open = commKeyConfigService
					.selectByDataKey("sms_open");

			if (sms_open != null && sms_open.getDataValue().equals("1")) {
				String content = String.format(
						CommSmsVerCodeMess.SMS_CONTENT, code);
				// 发送成功，返回0
				sendResult = client.sendSMS(phoneNos, content, 3);	
				
				logger.info(String.format("开启短信接口,手机号码是%s,验证码是%s,接口返回结果是%s", phoneNo,code,sendResult));
			} else {
				sendResult = 0;
				
				logger.info(String.format("关闭短信接口,手机号码是%s,验证码是%s,接口返回结果是%s", phoneNo,code,sendResult));
			}
		} catch (Exception e) {
			throw new RuntimeException("sms not available", e);
		}

		
		return sendResult;
	}

	@Override
	public boolean validate(String phoneNo, String type, String code) {
		CommKeyConfig sms_open = commKeyConfigService
				.selectByDataKey("sms_open");

		if (sms_open == null || sms_open.getDataKey().equals("0")) {
			return true;
		}
		CommSmsVerCode commSmsVerCode = commSmsVerCodeService
				.selectLastByMobileAndTypeAndCode(phoneNo, type, code);
		if (commSmsVerCode == null
				|| (new Date().getTime() - commSmsVerCode.getCreateTime()
						.getTime()) > 30 * 60 * 1000) {
			return false;
		}
		return true;
	}

}